# coding=utf-8
#
import datetime
import logging
import os

from apscheduler.schedulers.blocking import BlockingScheduler

import zipfile

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='myapp.log1.py',
                    filemode='w')

# 定义一个StreamHandler，将INFO级别或更高的日志信息打印到标准错误，并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

root_path = "/usr/local/apache-tomcat/log/"


def zip_files(zip_src):
    logging.info("begin zip ...")
    if (os.path.exists(root_path + zip_src) == False):
        logging.info(zip_src + " not found")
        return
    f = zipfile.ZipFile(root_path + zip_src + ".zip", 'w', zipfile.ZIP_DEFLATED)
    f.write(root_path + zip_src)
    f.close()
    logging.info("zip " + zip_src + " done")
    os.remove(root_path + zip_src)


def tick():
    logging.info('Tick! The time is: %s' % datetime.datetime.now())
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=-1)  # 获取前一天的日期
    n_days = now + delta
    yestoday = n_days.strftime('%Y-%m-%d')
    catalina_out = "catalina." + yestoday + ".out"
    zip_files(catalina_out)


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_job(tick, 'cron', hour='2')  # 每天两点执行
    # print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
